package com.flowplan.todo.controller;

import com.flowplan.auth.util.JwtTokenUtil;
import com.flowplan.common.dto.ApiResponse;
import com.flowplan.entity.enums.TodoStatus;
import com.flowplan.entity.enums.TodoType;
import com.flowplan.todo.dto.TodoCreateRequest;
import com.flowplan.todo.dto.TodoResponse;
import com.flowplan.todo.dto.TodoUpdateRequest;
import com.flowplan.todo.service.TodoService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 待办管理控制器
 * 
 * @author FlowPlan Team
 */
@Slf4j
@RestController
@RequestMapping("/todos")
public class TodoController {
    
    @Autowired
    private TodoService todoService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Value("${jwt.header}")
    private String tokenHeader;
    
    @Value("${jwt.prefix}")
    private String tokenPrefix;
    
    /**
     * 创建待办
     */
    @PostMapping
    public ResponseEntity<ApiResponse<TodoResponse>> createTodo(
            @Valid @RequestBody TodoCreateRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            TodoResponse response = todoService.createTodo(request, userId);
            return ResponseEntity.ok(ApiResponse.success("待办创建成功", response));
        } catch (Exception e) {
            log.error("创建待办失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "创建待办失败: " + e.getMessage()));
        }
    }
    
    /**
     * 更新待办
     */
    @PutMapping("/{todoId}")
    public ResponseEntity<ApiResponse<TodoResponse>> updateTodo(
            @PathVariable Long todoId,
            @Valid @RequestBody TodoUpdateRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            TodoResponse response = todoService.updateTodo(todoId, request, userId);
            return ResponseEntity.ok(ApiResponse.success("待办更新成功", response));
        } catch (Exception e) {
            log.error("更新待办失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "更新待办失败: " + e.getMessage()));
        }
    }
    
    /**
     * 删除待办
     */
    @DeleteMapping("/{todoId}")
    public ResponseEntity<ApiResponse<Void>> deleteTodo(
            @PathVariable Long todoId,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            todoService.deleteTodo(todoId, userId);
            return ResponseEntity.ok(ApiResponse.success("待办删除成功"));
        } catch (Exception e) {
            log.error("删除待办失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "删除待办失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取待办详情
     */
    @GetMapping("/{todoId}")
    public ResponseEntity<ApiResponse<TodoResponse>> getTodo(@PathVariable Long todoId) {
        try {
            TodoResponse response = todoService.getTodo(todoId);
            return ResponseEntity.ok(ApiResponse.success("获取待办详情成功", response));
        } catch (Exception e) {
            log.error("获取待办详情失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "获取待办详情失败: " + e.getMessage()));
        }
    }
    
    /**
     * 分页查询待办列表
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<TodoResponse>>> getTodos(
            @RequestParam(required = false) Long projectId,
            @RequestParam(required = false) TodoStatus status,
            @RequestParam(required = false) Long assigneeId,
            @RequestParam(required = false) TodoType todoType,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<TodoResponse> response = todoService.getTodos(projectId, status, assigneeId, todoType, keyword, page, size);
            return ResponseEntity.ok(ApiResponse.success("查询待办列表成功", response));
        } catch (Exception e) {
            log.error("查询待办列表失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "查询待办列表失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取当前用户相关的待办列表
     */
    @GetMapping("/my")
    public ResponseEntity<ApiResponse<List<TodoResponse>>> getMyTodos(HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            List<TodoResponse> response = todoService.getUserTodos(userId);
            return ResponseEntity.ok(ApiResponse.success("获取我的待办成功", response));
        } catch (Exception e) {
            log.error("获取我的待办失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "获取我的待办失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取项目下的待办列表
     */
    @GetMapping("/project/{projectId}")
    public ResponseEntity<ApiResponse<List<TodoResponse>>> getProjectTodos(@PathVariable Long projectId) {
        try {
            List<TodoResponse> response = todoService.getProjectTodos(projectId);
            return ResponseEntity.ok(ApiResponse.success("获取项目待办成功", response));
        } catch (Exception e) {
            log.error("获取项目待办失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "获取项目待办失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取即将到期的待办
     */
    @GetMapping("/near-deadline")
    public ResponseEntity<ApiResponse<List<TodoResponse>>> getTodosNearDeadline() {
        try {
            List<TodoResponse> response = todoService.getTodosNearDeadline();
            return ResponseEntity.ok(ApiResponse.success("获取即将到期待办成功", response));
        } catch (Exception e) {
            log.error("获取即将到期待办失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "获取即将到期待办失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取已过期的待办
     */
    @GetMapping("/overdue")
    public ResponseEntity<ApiResponse<List<TodoResponse>>> getOverdueTodos() {
        try {
            List<TodoResponse> response = todoService.getOverdueTodos();
            return ResponseEntity.ok(ApiResponse.success("获取已过期待办成功", response));
        } catch (Exception e) {
            log.error("获取已过期待办失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "获取已过期待办失败: " + e.getMessage()));
        }
    }
    
    /**
     * 更新待办状态
     */
    @PatchMapping("/{todoId}/status")
    public ResponseEntity<ApiResponse<TodoResponse>> updateTodoStatus(
            @PathVariable Long todoId,
            @RequestParam TodoStatus status,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            TodoResponse response = todoService.updateTodoStatus(todoId, status, userId);
            return ResponseEntity.ok(ApiResponse.success("待办状态更新成功", response));
        } catch (Exception e) {
            log.error("待办状态更新失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "待办状态更新失败: " + e.getMessage()));
        }
    }
    
    /**
     * 从Token中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String bearerToken = request.getHeader(tokenHeader);
        if (bearerToken != null && bearerToken.startsWith(tokenPrefix)) {
            String token = bearerToken.substring(tokenPrefix.length());
            return jwtTokenUtil.getUserIdFromToken(token);
        }
        throw new RuntimeException("无效的Token");
    }
}